package de.Ox539.nagroid;

import java.util.Calendar;
import java.util.StringTokenizer;

public class TimeRange {
	private int startHour;
	private int startMinute;
	private int endHour;
	private int endMinute;
	
	public int getStartHour() {
		return startHour;
	}

	public void setStartHour(int startHour) {
		this.startHour = startHour;
	}

	public int getStartMinute() {
		return startMinute;
	}

	public void setStartMinute(int startMinute) {
		this.startMinute = startMinute;
	}

	public int getEndHour() {
		return endHour;
	}

	public void setEndHour(int endHour) {
		this.endHour = endHour;
	}

	public int getEndMinute() {
		return endMinute;
	}

	public void setEndMinute(int endMinute) {
		this.endMinute = endMinute;
	}
	
	public String serialize() {
		return String.format("%d:%d-%d:%d", startHour, startMinute, endHour, endMinute);
	}
	
	static public TimeRange deserialize(String str) {
		TimeRange range = new TimeRange();
		if(str.length() == 0)
			return range;
		
		StringTokenizer tokenizer = new StringTokenizer(str, ":-");
		if(tokenizer.countTokens() != 4)
			throw new RuntimeException(String.format("FAIL: %d", tokenizer.countTokens()));
		
		range.startHour = Integer.parseInt(tokenizer.nextToken());
		range.startMinute = Integer.parseInt(tokenizer.nextToken());
		range.endHour = Integer.parseInt(tokenizer.nextToken());
		range.endMinute = Integer.parseInt(tokenizer.nextToken());
		return range;
	}
	
	final class Time {
		int hour;
		int minute;
		
		Time(int hour, int minute) {
			this.hour = hour;
			this.minute = minute;
		}
		
		boolean lessThan(Time other) {
			if(this.hour < other.hour)
				return true;
			if(this.hour == other.hour && this.minute < other.minute)
				return true;
			return false;
		}
		
		boolean equals(Time other) {
			return (this.hour == other.hour) && (this.minute == other.minute);
		}
		
		boolean lessOrEqualThan(Time other) {
			return this.equals(other) || this.lessThan(other);
		}
		
		void addDay() {
			hour += 24;
		}
	}
		
	public boolean inRange(int hour, int minute) {
		hour %= 24;
		
		final Time start = new Time(startHour, startMinute);
		Time end = new Time(endHour, endMinute);
		Time pointInTime = new Time(hour, minute);
		
		// Day wrapping.
		if(end.lessThan(start)) {
			end.addDay();
			if(pointInTime.lessThan(start))
				pointInTime.addDay();
		}
		
		return start.lessOrEqualThan(pointInTime) && pointInTime.lessThan(end);	
	}
		
	public boolean currentlyInRange() {
		final Calendar cal = Calendar.getInstance();
		final int currentHour = cal.get(Calendar.HOUR_OF_DAY);
		final int currentMinute = cal.get(Calendar.MINUTE);
		return inRange(currentHour, currentMinute);
	}
}
